<template>
  <div class="editor-page">
  <div class="container page">
    <div class="row">

      <div class="col-md-10 offset-md-1 col-xs-12">
        <form>
          <fieldset>
            <fieldset class="form-group">
              <input v-model="article.title" type="text" class="form-control form-control-lg" placeholder="Article Title">
            </fieldset>
            <fieldset class="form-group">
              <input v-model="article.description" type="text" class="form-control" placeholder="What's this article about?">
            </fieldset>
            <fieldset class="form-group">
              <textarea v-model="article.body" class="form-control" rows="8" placeholder="Write your article (in markdown)"></textarea>
            </fieldset>
            <fieldset class="form-group">
              <input type="text" class="form-control" placeholder="Enter tags" @keyup.enter="onAddTag">
              <div class="tag-list">
                <span
                  class="tag-default tag-pill"
                  v-for="(tag, index) in article.tagList"
                  :key="index">
                  <i class="ion-close-round" @click="onDeleteTag(index)"></i>
                  {{ tag }}
                </span>
              </div>
            </fieldset>
            <button class="btn btn-lg pull-xs-right btn-primary" type="button" @click="onSubmit">
              Publish Article
            </button>
          </fieldset>
        </form>
      </div>

    </div>
  </div>
</div>
</template>

<script>
import { createArticle, getArticle, updateArticle } from '@/api/article'
export default {
  name: 'EditorIndex',
  middleware: 'authenticated',
  data() {
    return {
      article: {
        title: "",
        description: "",
        body: "",
        tagList: []
      },
      errors: {}
    }
  },
  async mounted () {
    if (this.$route.name === 'editor-article') {
      const { data } = await getArticle(this.$route.params.slug)
      const { article } = data

      this.article = {
        title: article.title,
        description: article.description,
        body: article.body,
        tagList: article.tagList
      }
    }
  },
  methods: {
    async onSubmit () {
      try {
        const { data } = await createArticle({
          article: this.article
        })
        this.$router.push(`/article/${data.article.slug}`)
      } catch (err) {
        this.errors = err.response.data.errors
      }
    },
    onAddTag (e) {
      const tagValue = e.target.value
      const { tagList } = this.article
      const findItem = tagList.find(_ => _ === tagValue)

      if (!findItem) {
        tagList.push(tagValue)
        e.target.value = ''
      }
    },
    onDeleteTag(index) {
      const { tagList } = this.article
      tagList.splice(index, 1)
    }
  }
}
</script>

<style>

</style>